// 云函数入口文件
const cloud = require('wx-server-sdk');
const CryptoJS = require('crypto-js');

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});

/**
 * 生成腾讯云API签名
 * 参考: https://cloud.tencent.com/document/api/598/45307
 */
exports.main = async (event, context) => {
    try {
        const { params, secretId, secretKey, region = 'ap-guangzhou', endpoint = 'asr.tencentcloudapi.com' } = event;

        if (!params || !secretId || !secretKey) {
            return {
                success: false,
                error: '缺少必要的参数'
            };
        }

        // 腾讯云API签名V3实现
        const timestamp = Math.floor(Date.now() / 1000);
        const date = new Date(timestamp * 1000).toISOString().split('T')[0];

        // 1. 拼接规范请求串
        const httpRequestMethod = 'POST';
        const canonicalUri = '/';
        const canonicalQueryString = '';

        // 构建规范头部
        const canonicalHeaders =
            'content-type:application/json\n' +
            `host:${endpoint}\n`;

        const signedHeaders = 'content-type;host';

        // 请求体哈希
        const requestPayload = JSON.stringify(params);
        const hashedRequestPayload = CryptoJS.SHA256(requestPayload).toString(CryptoJS.enc.Hex);

        const canonicalRequest = [
            httpRequestMethod,
            canonicalUri,
            canonicalQueryString,
            canonicalHeaders,
            signedHeaders,
            hashedRequestPayload
        ].join('\n');

        // 2. 拼接待签名字符串
        const algorithm = 'TC3-HMAC-SHA256';
        const credentialScope = `${date}/asr/tc3_request`;

        // 计算规范请求串的哈希值
        const hashedCanonicalRequest = CryptoJS.SHA256(canonicalRequest).toString(CryptoJS.enc.Hex);

        const stringToSign = [
            algorithm,
            timestamp,
            credentialScope,
            hashedCanonicalRequest
        ].join('\n');

        // 3. 计算签名
        // 计算派生签名密钥
        function getSignatureKey(key, dateStamp, service) {
            const kDate = CryptoJS.HmacSHA256(dateStamp, 'TC3' + key);
            const kService = CryptoJS.HmacSHA256(service, kDate);
            const kSigning = CryptoJS.HmacSHA256('tc3_request', kService);
            return kSigning;
        }

        const signingKey = getSignatureKey(secretKey, date, 'asr');
        const signature = CryptoJS.HmacSHA256(stringToSign, signingKey).toString(CryptoJS.enc.Hex);

        // 4. 拼接 Authorization
        const authorization = `${algorithm} Credential=${secretId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;

        // 返回签名信息和时间戳
        return {
            success: true,
            authorization,
            timestamp,
            date,
            headers: {
                'Content-Type': 'application/json',
                'Host': endpoint,
                'X-TC-Action': params.Action,
                'X-TC-Version': params.Version || '2019-06-14',
                'X-TC-Region': region,
                'X-TC-Timestamp': timestamp.toString(),
                'Authorization': authorization
            }
        };
    } catch (error) {
        console.error('生成签名失败:', error);
        return {
            success: false,
            error: error.message || '签名生成失败'
        };
    }
}; 